<template>
  <div>
    <a-modal :width="850" title="选择租户" :visible="show" @cancel="cancel">
      <template slot="footer">
        <a-button @click="cancel">取消</a-button>
        <a-button key="submit" type="primary" @click="ok">确定</a-button>
      </template>
      <a-spin :spinning="spinning">
        <div class="employee-selector-wrapper2">
          <div>
            <div class="employee-selector-block">
              <a-input-search placeholder="输入租户名称" v-model="searchName" style="width: 100%" @search="searchPeople" />
            </div>
            <div class="tree-item2">
              <div>全选当页</div>
              <xq-icon type="icon-wancheng2" v-if="isAllSelected" @click="choseAll(treeData)" class="iconStyle"></xq-icon>
              <img
                v-else
                @click="choseAll(treeData)"
                src="@/assets/icons/未选择.png"
                style="width: 18px; height: 18px; margin-left: 10px"
              />
            </div>
            <div class="employee-selector">
              <div v-for="(item, index) in treeData" :key="index" class="mg_t10">
                <div class="tree-item" @click="chose(item, treeData)">
                  <span>
                    <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                    {{ item.name }}
                  </span>
                  <xq-icon v-on:click.stop="chose(item, treeData)" type="icon-wancheng2" v-if="item.isSelected" class="iconStyle"></xq-icon>
                  <img v-else v-on:click.stop="chose(item, treeData)" src="@/assets/icons/未选择.png" style="width: 18px; height: 18px" />
                </div>
              </div>
            </div>
            <a-pagination
              v-model="current"
              size="small"
              :page-size-options="pageSizeOptions"
              :total="total"
              show-size-changer
              show-less-items
              :page-size="pageSize"
              @showSizeChange="onShowSizeChange"
              @change="onPageChange"
            >
              <template slot="buildOptionText" slot-scope="props">
                <span>{{ props.value }}条/页</span>
              </template>
            </a-pagination>
          </div>
          <div class="verticalBar" />
          <div class="employee-selector-block2">
            <div class="employee-selector-title">已经选择的租户 {{ selectedListTemp.length }}个</div>
            <div class="employee-selector">
              <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
                <div>
                  <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                  {{ item.name }}
                </div>
                <img @click="deleteItem(item)" src="@/assets/icons/删除.png" style="width: 20px; height: 20px" />
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getWageEmp } from "@/api/company/contract";
import { selectSiteWithHr } from "./api";
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    defaultSelectedKeys: {
      type: Array,
      default: () => []
    },
    selectedList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      spinning: false,
      treeData: [],
      searchName: undefined,
      selectedListTemp: [],
      isAllSelected: false,
      pageSizeOptions: ["10", "20", "50", "100"],
      pageSize: 10,
      current: 1,
      total: 50
    };
  },
  watch: {
    show(val) {
      if (val) {
        this.selectedListTemp = this.selectedList;
        this.treeData = [];
        this.searchName = undefined;
        this.current = 1;
        this.spinning = false;
        this.getSelectDepTree();
      }
    }
  },

  methods: {
    // 分页变化
    onPageChange(pageNumber) {
      this.current = pageNumber;
      this.getSelectDepTree();
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.current = 1;
      this.getSelectDepTree();
    },
    choseAll(data) {
      this.isAllSelected = !this.isAllSelected;
      var that = this;
      this.spinning = true;
      for (var j = 0, len = data.length; j < len; j++) {
        data[j].isSelected = that.isAllSelected;
        that.ergodicAll(data[j]);
      }
      setTimeout(function () {
        that.spinning = false;
      }, "10");
    },
    chose(item, data) {
      item.isSelected = !item.isSelected;
      this.onChange(item);
    },
    onChangeTab(e) {
      this.isAllSelected = false;
      this.current = 1;

      this.getSelectDepTree();
    },
    onChange(item) {
      this.spinning = true;
      var that = this;
      setTimeout(function () {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    ergodic(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除

          this.treeData.some((e) => {
            if (e.id === item.id) {
              e.isSelected = false;
              return true;
            }
          });
          var allState = true;
          this.treeData.forEach((item, index) => {
            if (item.isSelected === false) {
              allState = false;
            }
          });
          this.isAllSelected = allState;
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
          var count = this.treeData.length;
          var allSelect = true;
          for (var o = 0; o < count; o++) {
            if (!this.treeData[o].isSelected) {
              allSelect = false;
              break;
            }
          }
          this.isAllSelected = allSelect;
        }
      }
    },
    ergodicAll(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
    },

    // 获取部门树
    getSelectDepTree(query) {
      if (query) {
        this.current = 1;
      }
      const params = {
        pageSize: this.pageSize,
        pageNo: this.current
      };
      if (this.searchName) {
        params["siteName"] = this.searchName;
      }
      this.spinning = true;
      selectSiteWithHr(params)
        .then((res) => {
          if (res.data.entities === null) {
            this.$message.success("暂无数据");
            this.treeData = [];
            this.total = 0;
            this.isAllSelected = false;
          } else {
            this.treeData = JSON.parse(JSON.stringify(this.formatCompanyData(res.data.entities)));
            this.total = res.data.entityCount;
            var count = res.data.entities.length;
            this.pageSize = res.data.pageSize;
            this.current = res.data.pageNo;
            var allSelect = true;
            this.spinning = false;
            if (count !== 0) {
              for (var i = 0; i < count; i++) {
                if (!this.treeData[i].isSelected) {
                  allSelect = false;
                  break;
                }
              }
              this.isAllSelected = allSelect;
            } else {
              this.isAllSelected = false;
            }
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.spinning = false;
        });
    },
    formatCompanyData(company) {
      const parent = [];
      for (var key = 0; key < company.length; key++) {
        var selected = false;

        this.selectedListTemp.forEach((item, index) => {
          if (item.id === company[key].id) {
            selected = true;
          }
        });
        var emp = {
          id: company[key].id,
          name: company[key].name,
          isSelected: selected
        };
        this.selectedListTemp.forEach((item, index) => {
          item.isSelected = true;
        });
        parent.push(emp);
      }

      return parent;
    },
    searchPeople(query) {
      this.searchName = query;
      this.getSelectDepTree();
    },
    deleteItem(item) {
      this.spinning = true;
      item.isSelected = false;
      // this.treeData.forEach((item2, index2) => {
      //   if (item2.id === item.id) {
      //     this.treeData[index2].isSelected = false;
      //   }
      // });
      var that = this;
      setTimeout(function () {
        that.ergodic(item);
        that.spinning = false;
      }, "10");
    },
    ok() {
      if (this.selectedListTemp.length === 0) {
        this.$message.success("请选择租户");
        return;
      }
      this.$emit("update:selectedList", this.selectedListTemp);
      this.$emit(
        "update:selectThree",
        this.selectedListTemp
          .slice(0, 3)
          .map((item) => item.name)
          .join(",")
      );
      this.$emit("update:show", false);
      this.$emit("change", this.selectedListTemp);
    },
    cancel() {
      this.$emit("update:show", false);
    }
  }
};
</script>
<style lang="scss" scoped>
.employee-selector {
  height: 410px;
  margin-top: 2px;
  padding-right: 10px;
  margin-bottom: 10px;
  overflow: auto;
}
.verticalBar {
  width: 1px;
  background: #e8e8e8;
  display: inline-block;
  margin-top: 40px;
  vertical-align: top;
  margin-right: 30px;
  margin-left: 30px;
  html,
  body,
  #app {
    height: 100%;
  }
}
.tree-item {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-bottom: 10px;
  margin-top: 24px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 400px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
  .employee-selector-block2 {
    width: 400px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 500px;
      margin-top: 20px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
}
.iconStyle {
  margin-left: 10px;
  font-size: 18px;
  color: var(--primary);
}
</style>
